import asyncRoutes from '@/router/modules/asyncRoutes';
import { RouteRecordRaw } from 'vue-router';

/**
 * 使用meta.role来确定当前用户是否有权限
 * @param roles
 * @param route
 */
function hasPermission(roles: (string | number)[], route: { meta: { roles: (string | number)[]; }; }) {
  if (route.meta && route.meta.roles) {
    return roles.some((role: string | number) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归通过权限过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
function filterAsyncRoutes(routes: RouteRecordRaw[], roles: (string | number)[]) {
  const res: RouteRecordRaw[] = []

  routes.forEach((route: any) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export default function(roles: Array<string | number>) {
  let accessedRoutes: RouteRecordRaw[]
  if (roles.includes('admin')) {
    accessedRoutes = asyncRoutes || []
  } else {
    accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  }
  return accessedRoutes
}